import 'package:flutter/material.dart';

class PaginationListViewModel with ChangeNotifier {
  var list = [];
  int pageId = 1;
  int pageSize = 20;
  bool isLoading = false;
  final ScrollController listCtrl = ScrollController();
  final Function(int pageId, int pageSize) future;

  PaginationListViewModel({required this.pageSize, required this.future}) {
    listCtrl.addListener(() {
      print("listCtrl:${listCtrl.positions.last.pixels}");
      print("maxScrollExtent:${listCtrl.positions.last.maxScrollExtent}");
      if (listCtrl.positions.last.pixels ==
          listCtrl.positions.last.maxScrollExtent ) {
        loadData();
      }
    });
  }

  void loadData() async {
    if(!isLoading) {
      isLoading = true;
      var res = await future(pageId, pageSize);
      if (res != null) {
        List list = res;
        if (list.isNotEmpty) {
          this.list.addAll(list);
          pageId++;
        }
      }
      isLoading = false;
      notifyListeners();
    }
  }

  void refresh() {
    pageId = 1;
    list = [];
    loadData();
  }

  void removeItem(item) {
    list.remove(item);
    notifyListeners();
  }

  void dispose() {
    list = [];
    listCtrl.dispose();
  }
}
